package com.sailfish.springbootdemo.controller.db2;

import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.service.db2.PcbNewTechnologyService;
import com.sailfish.springbootdemo.service.db2.S3UploadFileService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import com.sailfish.springbootdemo.utils.SfsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/pcbNewTechnology")
public class PcbNewTechnologyController {

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;
    @Value("${personal.config.env}")
    private String env;
    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;

    @Autowired
    SfsUtils sfsUtils;
    @Autowired
    PcbNewTechnologyService pcbNewTechnologyService;
    @Autowired
    S3UploadFileService s3UploadFileService;

    //获取参数列表
    @PostMapping("/getAllPcbNewTechnologyParam")
    public Result getAllPcbMaterialParam(Integer status) {
        PcbNewTechnologyParam search = new PcbNewTechnologyParam();
        search.setStatus(status);
        List<PcbNewTechnologyParam> allPcbNewTechnologyParam = pcbNewTechnologyService.getAllPcbNewTechnologyParam(search);
        return ResultUtil.success(allPcbNewTechnologyParam);
    }

    //添加或更新参数列表
    @PostMapping("/insertOrUpdatePcbNewTechnologyParam")
    public Result insertOrUpdatePcbNewTechnologyParam(Integer paramId, String paramName, String paramNameEn, String paramKey, Integer paramType, Integer isRequired, String paramOptions, String remark, Integer status, Integer sort) {

        PcbNewTechnologyParam param = new PcbNewTechnologyParam();
        if (StringUtils.isBlank(paramName) && StringUtils.isBlank(paramNameEn)) {
            return ResultUtil.error(500, "参数名为空", "", null);
        }
        param.setParamId(paramId);
        param.setParamName(paramName);
        param.setParamNameEn(paramNameEn);
        param.setParamKey(paramKey);
        param.setParamType(paramType);
        param.setIsRequired(isRequired);
        param.setParamOptions(paramOptions);
        param.setRemark(remark);
        param.setStatus(status);
        param.setSort(sort);
        if (paramId == null) {
            param.setCreateTime(new Date());
        } else {
            param.setUpdateTime(new Date());
        }
        return pcbNewTechnologyService.insertOrUpdatePcbNewTechnologyParam(param);
    }

    //删除参数列表
    @PostMapping("/deletePcbNewTechnologyParam")
    public Result deletePcbNewTechnologyParam(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "", null);
        }
        return pcbNewTechnologyService.deletePcbNewTechnologyParam(id);
    }

    //判断能否删除
    @PostMapping("/checkPcbNewTechnologyHasData")
    public Result checkPcbNewTechnologyHasData(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "", null);
        }
        return pcbNewTechnologyService.checkPcbNewTechnologyHasData(id);
    }

    //获取新技术库
    @PostMapping("/getNewTechnologyLibrary")
    public Result getNewTechnologyLibrary(String approveStatus,String searchK,String searchV) {
        List<PcbNewTechnologyLibrary> params = null;
        if(!StringUtils.isBlank(searchK)){
            PcbNewTechnologyLibrary search = new PcbNewTechnologyLibrary();
            search.setParamKey(searchK);
            search.setParamValue(searchV);
            params = new ArrayList<>();
            params.add(search);
        }
        Map<String, NewTechnologyInfo> allPcbNewTechnologyLibrary = pcbNewTechnologyService.getAllPcbNewTechnologyLibrary(params, approveStatus);
        return ResultUtil.success(allPcbNewTechnologyLibrary);
    }

    //添加或更新新技术库
    @PostMapping("/insertOrUpdateNewTechnologyLibrary")
    public Result insertOrUpdateNewTechnologyLibrary(@RequestBody String data) {
        return pcbNewTechnologyService.insertOrUpdatePcbNewTechnologyLibrary(data);
    }

    //删除新技术库
    @PostMapping("/deleteNewTechnologyLibrary")
    public Result deleteNewTechnologyLibrary(String rowKey) {
        return pcbNewTechnologyService.deletePcbNewTechnologyLibrary(rowKey, null);
    }

    //更新新技术库的固定字段
    @PostMapping("/updateNewTechnologyLibraryStatus")
    public Result updateNewTechnologyLibraryStatus(String rowKey, String remark, String approveStatus, Integer approverUserId) {
//        String userId = UserHeaderHolder.getUserId();
//        Integer approverUserId = Integer.parseInt(userId);

        return pcbNewTechnologyService.updatePcbNewTechnologyStatus(rowKey, null, null, null, remark, approveStatus, approverUserId);
    }

    //提交审核
    @PostMapping("/updateApproveStatus")
    public Result updateApproveStatus(String status, Integer id, Integer approveUser, String remark) {
        return pcbNewTechnologyService.updateStatus(status, id, approveUser, remark);
    }

    /**
     * 上传图片
     *
     * @param req
     * @return
     */
    @PostMapping("/uploadPicture")
    public Result uploadPicture(HttpServletRequest req) {
        try {
            String userId = UserHeaderHolder.getUserId();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
            if (!StringUtils.isBlank(env)) {
                Map<String, String> map = new HashMap<>();

                if (env.equals("dev")) {
                    //获取项目目录
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(new Date());
                    File folder = new File(fileSaveUrl + "pcb\\" + format);
                    String filePath = "";
                    if (!folder.isDirectory()) {
                        folder.mkdirs();
                    }
                    file.transferTo(new File(folder, newName));
                    filePath = "pcb\\" + format + "\\" + newName;
                    map.put("name", newName);
                    map.put("oldName", oldName);
                    map.put("relatePath", filePath);
                    String base64 = "";
                    base64 = s3UploadFileService.getImageBase64FromUrl(filePath);
                    map.put("imageBase64", CommonUtils.base64Prefix() + base64);
                    return ResultUtil.success(map);
                } else {
                    String address = s3UploadFileService.uploadFile("pcb", file);
                    if (address == null) {
                        return ResultUtil.error(500, "上传图片接口错误", null, null);
                    } else {
//                        String address = "11.jpg";
                        map.put("oldName", oldName);
                        map.put("name", newName);
                        map.put("relatePath", address);
                        map.put("url", url + "/" + fileBucket + "/" + address);
                        String base64 = "";
                        base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + address);
                        map.put("imageBase64", CommonUtils.base64Prefix() + base64);
//                        map.put("url","http://192.168.31.11:2900/capacityApi/capacityFiles/pcb/2023-10-18/6d258ebc-399c-4533-9287-94af347cad65.png");
                        return ResultUtil.success(map);
                    }
                }
            } else {
                return ResultUtil.error(500, "配置文件yml中未定义参数：env", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 上传文件
     *
     * @param req
     * @return
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(HttpServletRequest req) {
        try {
            String userId = UserHeaderHolder.getUserId();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");
            if (!StringUtils.isBlank(env)) {
                Map<String, String> map = new HashMap<>();
                String oldName = file.getOriginalFilename();
                if (env.equals("dev")) {
                    //获取项目目录
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(new Date());
                    File folder = new File(fileSaveUrl + "pcb\\" + format);

                    String filePath = "";
                    if (!folder.isDirectory()) {
                        folder.mkdirs();
                    }

                    String newName = UUID.randomUUID().toString() +
                            oldName.substring(oldName.lastIndexOf("."), oldName.length());

                    file.transferTo(new File(folder, newName));
                    filePath = "pcb\\" + format + "\\" + newName;
                    map.put("name", newName);
                    map.put("oldName", oldName);
                    map.put("relatePath", filePath);
                    return ResultUtil.success(map);
                } else {

                    String secretKey = String.valueOf(UUID.randomUUID()).substring(0, 30);
                    SfsUtils.SfsFileData data = sfsUtils.upload(file, secretKey);
                    if (data == null) {
                        return ResultUtil.error(500, "上传接口返回data为空", null, null);
                    } else {
                        String fileSid = data.getFileSid();
//                        String fileSid = "10203";
                        if (StringUtils.isBlank(fileSid)) {
                            return ResultUtil.error(500, "上传接口返回data.fileSid为空", null, null);
                        }
                        map.put("oldName", oldName);
                        map.put("secretKey", secretKey);
                        map.put("fileSid", fileSid);
                        return ResultUtil.success(map);
                    }
                }
            } else {
                return ResultUtil.error(500, "配置文件yml中未定义参数：env", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("previewUrl")
    public Result previewUrl(Integer fileId) {
        try {
            PcbNewTechnologyFile pcbNewTechnologyFile = pcbNewTechnologyService.getFileById(fileId);
            String fileSid = pcbNewTechnologyFile.getFileSid();
            String secretKey = pcbNewTechnologyFile.getSecretKey();
            SfsUtils.SfsFileData data = sfsUtils.preview(fileSid, secretKey);
            return ResultUtil.success(data);
        } catch (Exception e) {
            return ResultUtil.error(500, "downloadH3CFile Exception:" + e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/downloadH3CFile")
    public Result downloadH3CFile(Integer fileId) {
        try {
            if (fileId == null) {
                return ResultUtil.error(500, "参数fileId为空", "param fileId is null", null);
            }
            PcbNewTechnologyFile pcbNewTechnologyFile = pcbNewTechnologyService.getFileById(fileId);
            String fileSid = pcbNewTechnologyFile.getFileSid();
            String secretKey = pcbNewTechnologyFile.getSecretKey();
            InputStream inputStream = sfsUtils.download(fileSid, secretKey);
            byte[] data = null;
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(data);
            Map<String, Object> map = new HashMap<>();
            map.put("base64", base64);
            map.put("fileName", pcbNewTechnologyFile.getFileName());
            return ResultUtil.success(map);
        } catch (Exception e) {
            return ResultUtil.error(500, "downloadH3CFile Exception:" + e.getMessage(), e.getMessage(), null);
        }
    }


    @GetMapping("/test")
    public Result test() throws IOException {
        String str = s3UploadFileService.getImageBase64FromUrl("http://192.168.31.11:2900/capacityApi/capacityFiles/pcb/2023-10-18/6d258ebc-399c-4533-9287-94af347cad65.png");
        return ResultUtil.success(str);
    }

//    @PostMapping("/getAllPcbNewTechnology")//String pcbTechnologyDesc,String pcbTechnologyAdvantage,String pcbTechnologyDevStatus,String valueAnalysis,String pcbTechnologyStatus,Integer responsibilityUser
//    public Result getAllPcbNewTechnology(String search, Integer pageSize,Integer page,String approveStatus,String type){
//        if(pageSize == null || !CommonUtils.isNumeric(pageSize.toString())){
//            return ResultUtil.error(500, "错误参数pageSize","Error Param pageSize",null);
//        }
//        if(page == null || !CommonUtils.isNumeric(page.toString())){
//            return ResultUtil.error(500, "错误参数page","Error Param page",null);
//        }
//        String userId = UserHeaderHolder.getUserId();
//        Integer approveUserId = null;
//        if(type != null && type.equals("approve") ){
//            approveUserId = Integer.parseInt(userId);
//        }
//        return  pcbNewTechnologyService.getAllByLimit(search,approveStatus,approveUserId,null,null,pageSize,page);
//    }
//
//    @PostMapping("/insertOrUpdatePcbNewTechnology")
//    public Result insertOrUpdatePcbNewTechnology(@RequestBody String data){
//        try
//        {
//            JSONObject jsonObject = JSONObject.parseObject(data);
//            String mode = jsonObject.getString("mode");
//            Integer pcbNewTechnologyInfoId = jsonObject.getInteger("pcbNewTechnologyInfoId");
//            Date proposedTime = jsonObject.getDate("proposedTime");
//            String pcbTechnologyDesc = jsonObject.getString("pcbTechnologyDesc");
//            String pcbTechnologyAdvantage = jsonObject.getString("pcbTechnologyAdvantage");
//            String pcbTechnologyDevStatus = jsonObject.getString("pcbTechnologyDevStatus");
//            String valueAnalysis = jsonObject.getString("valueAnalysis");
//            String pcbTechnologyStatus = jsonObject.getString("pcbTechnologyStatus");
//            Integer responsibilityUserId = jsonObject.getInteger("responsibilityUserId");
//            String responsibilityUserName = jsonObject.getString("responsibilityUserName");
//            JSONArray jsonArray = jsonObject.getJSONArray("picList");
//            List<PcbNewTechnologyPic> pcbNewTechnologyPics = JSONArray.parseArray(jsonArray.toJSONString(), PcbNewTechnologyPic.class);
//
//            PcbNewTechnologyInfo param = new PcbNewTechnologyInfo();
//            param.setPicList(pcbNewTechnologyPics);
//            param.setPcbTechnologyDesc(pcbTechnologyDesc);
//            param.setPcbTechnologyAdvantage(pcbTechnologyAdvantage);
//            param.setPcbTechnologyDevStatus(pcbTechnologyDevStatus);
//            param.setValueAnalysis(valueAnalysis);
//            param.setPcbTechnologyStatus(pcbTechnologyStatus);
//            param.setResponsibilityUserId(responsibilityUserId);
//            param.setResponsibilityUserName(responsibilityUserName);
//            param.setProposedTime(proposedTime);
//            if(mode.equals("update") ){
//                if(pcbNewTechnologyInfoId == null){
//                    return ResultUtil.error(500,"参数pcbNewTechnologyInfoId为空","param pcbNewTechnologyInfoId miss",null);
//                }
//                param.setPcbNewTechnologyInfoId(pcbNewTechnologyInfoId);
//                param.setUpdateTime(new Date());
//                pcbNewTechnologyService.update(param);
//            }
//            else{
//                param.setApproveStatus("待分配");
//                param.setCreateTime(new Date());
//                param.setStatus(1);
//                param.setSort(100);
//                pcbNewTechnologyService.insert(param);
//            }
//            return ResultUtil.success(null);
//        }
//        catch (Exception e){
//            e.printStackTrace();
//            return ResultUtil.error(500,e.getMessage(),e.getMessage(),null);
//        }
//
//    }
//
//    @PostMapping("/deletePcbNewTechnology")
//    public Result deletePcbNewTechnology(Integer pcbNewTechnologyInfoId){
//
//        return pcbNewTechnologyService.delete(pcbNewTechnologyInfoId);
//    }

    //导出Excel
    /*@PostMapping("/createExcel")
    public Result createExcel(String approveStatus,String searchK,String searchV) {
        try {
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("xx工厂线体设备整线能力反馈报告");
            // 创建行和单元格对象
            Row row = sheet.createRow(0);
            CellStyle contextCellStyle = workbook.createCellStyle();
            contextCellStyle.setBorderBottom(BorderStyle.THIN);
            contextCellStyle.setBorderLeft(BorderStyle.THIN);
            contextCellStyle.setBorderRight(BorderStyle.THIN);
            contextCellStyle.setBorderTop(BorderStyle.THIN);
            List<String> titleList = new ArrayList<>();
            titleList.add("序号");
            titleList.add("技术说明");
            titleList.add("技术分类");
            titleList.add("技术优点");
            titleList.add("开发状态");
            titleList.add("附件说明");
            titleList.add("价值分析");
            titleList.add("任务状态");
            titleList.add("闭环责任人");
            titleList.add("审批状态");
            titleList.add("审批人");
            for (int a = 0; a < 11; a++) {
                sheet.setColumnWidth(a, 900 * 10);
                Cell cell = row.createCell(a);
                // 向单元格中写入数据
                cell.setCellValue(titleList.get(a));
                cell.setCellStyle(contextCellStyle);
            }
            // 开始添加数据行示例
            List<List<String>> dataList = new ArrayList<>();
            List<PcbNewTechnologyLibrary> params = null;
            if(!StringUtils.isBlank(searchK)){
                PcbNewTechnologyLibrary search = new PcbNewTechnologyLibrary();
                search.setParamKey(searchK);
                search.setParamValue(searchV);
                params = new ArrayList<>();
                params.add(search);
            }
            Map<String, NewTechnologyInfo> allPcbNewTechnologyLibrary = pcbNewTechnologyService.getAllPcbNewTechnologyLibrary(params, approveStatus);

            List<String> dataRow1 = new ArrayList<>();
            PcbNewTechnologyLibrary search = new PcbNewTechnologyLibrary();
            params.add(search);
            dataList.add(dataRow1);
            for (int i = 0; i < dataList.size(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                List<String> rowData = dataList.get(i);
                for (int j = 0; j < rowData.size(); j++) {
                    Cell cell = dataRow.createCell(j);
                    cell.setCellValue(rowData.get(j));
                }
            }
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream("output.xlsx");
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }*/
}
